<template>
	<div class="app-container">
		<div class="bgWhite radius8">
			<el-form class="p20 flex col-top row-between" style="padding-bottom: 0;" label-width="100px"
				:model="queryParams" ref="queryForm" :inline="true">
				<div>
					<el-form-item label="关键词" prop="keyword">
						<el-input v-model="queryParams.keyword" placeholder="请输入关键词" clearable class="resetInput"
							style="width: 200px" :suffix-icon="Search" @keyup.enter="handleQuery" />
					</el-form-item>
					<el-form-item label="选择日期" prop="time">
						<el-date-picker 
						v-model="queryParams.time" 
						value-format="YYYY-MM-DD"
						type="daterange"
						range-separator="至"
						start-placeholder="请选择开始时间"
						end-placeholder="请选择结束时间"
						placeholder="" size="large"/>
					</el-form-item>
				</div>
				<el-form-item>
					<div class="flex col-center row-end" style="margin-right: 0">
						<el-button class="searchBtn" type="defaultBtn" @click="handleQuery">查询</el-button>
						<el-button class="searchBtn" icon="Refresh" @click="resetQuery">重置</el-button>
					</div>
				</el-form-item>
			</el-form>
		</div>
		<div class="bgWhite radius8 p20 mt25">
			<div class="flex col-center row-between mb20">
				<span class="fb fs16">原料价格列表</span>
				<div class="flex col-center">
					<el-button type="operate" style="width: 70px;"
						v-hasPermi="['raw_material_price:importAdd']"
						@click="importRaw()">导入</el-button>
					<el-button type="operate" style="width: 100px;"
						@click="updataPrice()" v-hasPermi="['raw_material_price:batchImportUpdate']">
						批量更新价格</el-button>
					<el-button type="defaultBtn" @click="handleAdd(0)" style="width: 86px;"
					v-hasPermi="['raw_material_price:add']"
					>
						新增原材料
					</el-button>
				</div>
			</div>
			<el-table v-loading="loading" :data="list" style="width: 100%" :header-row-style="{
					background: '#FAFAFA',
					color: '#0C1019',
					height: '54px',
				  }" :cell-style="{ height: '54px' }">
				<el-table-column label="原料名称" align="center" prop="materialName">
					<template #default="scope">
						<span class="main-color">{{scope.row.materialName}}</span>
					</template>
				</el-table-column>
				<el-table-column label="原料ID" align="center" prop="materialId" width="120"/>
				<el-table-column label="最新价格（元/吨）" align="center" prop="latestPrice"/>
				<el-table-column label="更新时间" align="center" prop="updateTime"/>
				<el-table-column label="更新人" align="center" prop="updatePerson"/>
				<el-table-column fixed="right" label="操作" align="center" width="200">
					<template v-slot="scope">
						<el-button size="mini" type="text" @click="handleAdd(1,scope.row)"
						v-hasPermi="['raw_material_price:edit']"
							>更新价格</el-button>
						<el-button size="mini" type="text" @click="handlePrice(scope.row)"
						v-hasPermi="['rawmaterial_price_history:check']"
							>查看历史价格</el-button>
					</template>
				</el-table-column>
			</el-table>
			<pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
								v-model:limit="queryParams.pageSize" @pagination="getList" />
		</div>
		<!-- 新增 -->
		<el-dialog v-model="dialogFormVisible" width="496" :title="type == 0 ? '新增原材料' : '更新价格'" center
		 :align-center="true"
			custom-class="radius8">
			<el-form :model="form" class="mt20" ref="formRef" :rules="rules" label-width="110px">
				<el-form-item label="原材料名称" prop="materialName">
					<el-input :disabled="type == 0 ? false : true" size="large" v-model="form.materialName" placeholder="请填写"></el-input>
					<!-- <div v-else>{{form.materialName}}</div> -->
				</el-form-item>
				<el-form-item label="原材料ID" prop="id">
					<el-input v-if="type == 0"  size="large" v-model="form.id" placeholder="请输入ID"></el-input>
					<div v-else>{{form.id}}</div>
				</el-form-item>
				<el-form-item label="最新价格" prop="latestPrice">
					<el-input size="large" type="number" min="0" v-model="form.latestPrice" placeholder="请输入金额"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer text-right mt30">
				<el-button class="cancelSubBtn" @click="dialogFormVisible = false">取 消</el-button>
				<el-button type="primary" @click="upDatePrice('formRef')" class="mainSubBtn">确 定</el-button>
			</div>
		</el-dialog>
		<!-- 批量更新 -->
		<el-dialog :title="importType == 1 ? '批量更新' : '批量导入'" center v-model="upload.open" width="694px" append-to-body>
		   <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
		      :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
		      :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
				<div>
					<div class="flex col-top">
						<img src="@/assets/images/Img.png" width="80" height="80" alt="" />
						<div class="text-left ml15 mt5" style="text-align: left;">
							<span class="fb color333 mr5 mt5">上传最新的价格文件</span>
							<el-link type="primary" :underline="false" 
							style="font-size:12px;vertical-align: baseline;border: 1px solid #4DACB1;background: #EDF6F7;border-radius: 2px;line-height: 22px;padding: 0 4px;"
							   @click.stop="importTemplate">下载模板</el-link>
							<div class="fs12 mt6 mb8">
								 <span>文件后缀名必须为xls 或xlsx（即Excel格式），文件大小不得大于10M，最多支持导入3000条数据</span>
							</div> 
							 <div class="main-color fs12">上传文件</div>
						</div>
					</div>
				</div>
		   </el-upload>
		   <template #footer>
		      <div class="dialog-footer text-right">
				   <el-button class="cancelSubBtn" @click="upload.open = false">取 消</el-button>
				   <el-button type="primary" @click="submitFileForm" class="mainSubBtn">确 定</el-button>
		      </div>
		   </template>
		</el-dialog>
		<!-- 导入字段 -->
		<el-dialog v-model="dialogFormVisible1" width="524" title="模板字段" center :align-center="true"
			custom-class="radius8">
			<el-table :data="list" style="width: 100%;text-align: center;"
				:cell-style="{ textAlign: 'center','line-height':'54px'}"
				:header-cell-style="{ 'text-align': 'center','line-height':'54px','height':'54px!important'  }"
				>
				<el-table-column prop="cropName" label="原材料名称">
					<template v-slot="scope">
						<span class="main-color">11</span>
					</template>
				</el-table-column>
				<el-table-column prop="cropName" label="原材料ID" />
				<el-table-column prop="cropName" label="最新价格（元/吨）">
					<template v-slot="scope">
					1111
					</template>
				</el-table-column>
			</el-table>	
		</el-dialog>	
	</div>
</template>

<script setup name="ProductSetup">
	import {
		rawList, //列表
		updataRawPrice,//更新价格
		addRawPrice//新增原材料
	} from "@/api/business/cost";
	import {
		Search
	} from '@element-plus/icons-vue'
	import {
		getDivisions
	} from "@/api/business/opportunity";//地址
</script>
<script>
	import { getToken } from "@/utils/auth";
	export default {
		data() {
			return {
				dialogFormVisible1:false,//模板字段
				loading: true, // 遮罩层
				total: 0, // 总条数
				list: [], // 表格数据
				queryParams: {
					pageNum: 1,
					pageSize: 10,
					keyword: '', // 
					time:[]
				}, //查询参数
				dialogFormVisible:false,
				form:{
					materialName:'',
					id:'',
					latestPrice:''
				},
				rules:{
					materialName: [
						{required: true,message: '请填写原材料名称',trigger: 'blur'},
					],
					id: [
						{required: true,message: '请填写ID',trigger: 'blur'},
					]
				},
				type:0,//新增
				upload:{
				   // 是否显示弹出层（用户导入）
				   open: false,
				   // 弹出层标题（用户导入）
				   title: "",
				   // 是否禁用上传
				   isUploading: false,
				   // 是否更新已经存在的用户数据
				   updateSupport: 0,
				   // 设置上传的请求头部
				   headers: { Authorization: "Bearer " + getToken() },
				   // 上传的地址
				   url: ''
				},
				importType:0//0导入 1：更新价格
			}
		},
		created() {
			this.getList()
		},
		methods: {	
			//导入
			importRaw(){
				this.importType = 0
				this.upload.open = true	
				this.upload.url = import.meta.env.VITE_APP_BASE_API+'/raw_material_price/importAdd'
			},
			// 批量更新价格
			updataPrice(){
				this.importType = 1
				this.upload.open = true	
				this.upload.url = import.meta.env.VITE_APP_BASE_API+'/raw_material_price/batchImportUpdate'
			},
			/** 下载模板操作 */
			importTemplate() {
			   this.download("/raw_material_price/templateDownload", {
			   }, `raw_material_price${new Date().getTime()}.xlsx`);
			},
			/**文件上传中处理 */
			handleFileUploadProgress(event, file, fileList) {
			   this.upload.isUploading = true;
			},
			/** 文件上传成功处理 */
			handleFileSuccess(response, file, fileList){
			   this.upload.open = false;
			   this.upload.isUploading = false;
			   this.$refs["uploadRef"].handleRemove(file);
			   this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
			   this.getList();
			},
			submitFileForm() {
			   this.$refs["uploadRef"].submit();
			},
			//查询作物列表
			getList() {
				this.loading = true;
				rawList(this.queryParams).then((response) => {
					this.list = response.rows;
					this.total = response.total;
					this.loading = false;
				});
			},
			/** 搜索按钮操作 */
			handleQuery() {
				this.queryParams.pageNum = 1;
				this.queryParams.startTime = this.queryParams.time.length > 0 ? this.queryParams.time[0]+' '+'00:00:00' : ''
				this.queryParams.endTime = this.queryParams.time.length > 0 ? this.queryParams.time[1]+' '+'23:59:59' : ''
				this.getList();
			},
			/** 重置按钮操作 */
			resetQuery() {
				this.resetForm("queryForm");
				this.handleQuery();
			},
			// 启用状态操作
			updateEnabled(row) {
				this.loading = true;
				let item = {
					id: row.id,
					status: row.status,
				}
				updateProduct(item).then((response) => {
					this.$modal.msgSuccess("启用状态更新成功");
					this.loading = false;
					this.getList();
				});
			},
			//更新价格
			handleAdd(num,row) {
				this.type = num
				this.form = {
					materialName:'',
					id:'',
					latestPrice:''
				}
				this.dialogFormVisible = true
				if(row){
					this.form = {
						materialName:row.materialName,
						id:row.id,
						latestPrice:row.latestPrice
					}
				}
			},
			//更新价格
			upDatePrice(formName){
				if(this.type == 0){
					//新增
					this.$refs[formName].validate((valid) => {
						if (valid) {
							delete this.form.id
							this.form.materialId = this.form.id
							addRawPrice(this.form).then(res=>{
								this.$modal.msgSuccess("添加成功");
								this.dialogFormVisible = false
								this.getList()
							})
						}
					})	
				}else{
					//编辑
					updataRawPrice(this.form).then(res=>{
						this.$modal.msgSuccess("编辑成功");
						this.dialogFormVisible = false
						this.getList()
					})
				}
			},
			// 查看历史
			handlePrice(row) {
				this.$router.push('/cost/costPrice?id=' + row.id)
			}
		}
	}
</script>